package com.solution.admin.coupon.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.solution.admin.coupon.constants.CouponConstants;
import com.solution.admin.coupon.constants.CouponConstants.IsUsed;
import com.solution.admin.coupon.dao.CouponDao;
import com.solution.admin.coupon.dao.CouponGetDao;
import com.solution.admin.coupon.dao.CouponGetRuleDao;
import com.solution.admin.coupon.entity.CouponEntity;
import com.solution.admin.coupon.entity.CouponGetEntity;
import com.solution.admin.coupon.entity.CouponGetRuleEntity;
import com.solution.admin.coupon.entity.CouponTargetDTO;
import com.solution.admin.coupon.service.CouponService;
import com.solution.common.constants.PublicStatus.IS_DELETE;
import com.solution.common.constants.PublicStatus.STATUS;
import com.solution.common.dao.BaseDao;
import com.solution.common.exception.BizException;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.service.impl.BaseServiceImpl;
import com.solution.common.utils.DateUtils;
import com.solution.common.utils.string.StringUtil;

/**
 * 优惠券信息service实现层
 * 
 * @author xu_cc
 * @date 2017-11-16 11:11:20
 */
@Service
public class CouponServiceImpl extends BaseServiceImpl<CouponEntity> implements CouponService {

    /**
     * 优惠券信息接口
     */
    @Autowired
    private CouponDao couponDao;

    @Autowired
    private CouponGetDao couponGetDao;
    
    @Autowired
    private CouponGetRuleDao couponGetRuleDao;

    protected BaseDao<CouponEntity> getDao() {
        return this.couponDao;
    }

    /**
     * 优惠券使用（将已领取的优惠券标识为已用，插入使用记录）
     * 
     * @param couponGetId
     * @param billCode
     * @param couponId
     *            清空缓存用
     * @return int
     * @author xu_cc
     * @throws Exception
     *             exception
     * @Date 创建时间：2017年11月17日 上午11:32:31
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int doUseCoupon(Long couponGetId, String userCode, String billCode, Long couponId) throws Exception {
        CouponGetEntity couponGet = couponGetDao.getById(couponGetId);
        if (IsUsed.USED.equals(couponGet.getIsUsed())) {
            throw new Exception("优惠券已被使用！");
        }
        // 获取优惠券信息
        CouponEntity coupon = couponDao.getById(couponGet.getCouponId());
        // 状态验证、是否删除验证
        if (STATUS.DISABLED.getId().equals(coupon.getStatus())) {
            throw new Exception("该优惠券已暂停使用！");
        }
        if (IS_DELETE.DELETED.getId().equals(coupon.getIsDelete())) {
            throw new Exception("该优惠券已作废，不可使用！");
        }
        // 领取时间验证
        Date currentDate = new Date();
        if (!(couponGet.getBeginTime().before(currentDate) && couponGet.getEndTime().after(currentDate))) {
            String beginGetDateStr = DateUtils.formatDateTime(couponGet.getBeginTime());
            String endGetDateStr = DateUtils.formatDateTime(couponGet.getEndTime());
            throw new Exception("当前时间无法使用该优惠券，优惠券使用时间是[" + beginGetDateStr + " ~ " + endGetDateStr + "]！");
        }
        // 使用表
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("couponGetId", couponGetId);
        paramMap.put("isUsed", IsUsed.USED);
        List<CouponGetEntity> usedList = couponGetDao.listCouponGet(paramMap);
        if (null != usedList && usedList.size() > 0) {
            throw new Exception("优惠券已经用过了！");
        }
        // 先更新
        CouponGetEntity couponGetMod = new CouponGetEntity();
        couponGetMod.setId(couponGetId);
        couponGetMod.setIsUsed(IsUsed.USED);
        couponGetMod.setUsedTime(new Date());
        couponGetDao.update(couponGetMod);
        return 1;
    }

    /**
     * 保存优惠券信息
     * @param couponEntity 优惠券信息实体
     * @return Long 添加成功优惠券信息的ID
     * @author xu_cc
     * @date 2017-11-16 11:11:20
     */
    @Transactional(propagation = Propagation.REQUIRED ,rollbackFor = Exception.class)
    public long saveCoupon(CouponEntity coupon) {
    	// 保存优惠券
		Long couponId;
		try {
			couponId = couponDao.saveCoupon(coupon);
			// 删除优惠券已经使用的类
			couponGetRuleDao.deleteRuleByCoupon(couponId);
			
			// 保存领取、使用限制类型
			String getTargetList = coupon.getGetTargetList();
			if(StringUtil.isNotEmpty(getTargetList)){
				List<CouponTargetDTO> tmpTargetList = JSONArray.parseArray(getTargetList, CouponTargetDTO.class);
				for (CouponTargetDTO target : tmpTargetList) {
					CouponGetRuleEntity couponRule = new CouponGetRuleEntity();
			    	couponRule.setCouponId(couponId);
					String targetVal = target.getTargetVal().replace(CouponConstants.GET_TARGET_PREFFIX.get(coupon.getGetTargetType()), "");
					couponRule.setTargetType(CouponConstants.COUPON_TARGET_TYPE.GET.getCode());
					couponRule.setTargetLimitType(coupon.getGetTargetType());
					couponRule.setTargetPro(target.getTargetPro());
					couponRule.setTargetVal(targetVal);
					couponRule.setCreater(coupon.getCreater());
					couponRule.setCreateTime(new Date());
					couponGetRuleDao.insert(couponRule);
				}
			}
			
			// 保存领取、使用限制类型
			String useTargetList = coupon.getGetTargetList();
			if(StringUtil.isNotEmpty(useTargetList)){
				List<CouponTargetDTO> tmpTargetList = JSONArray.parseArray(useTargetList, CouponTargetDTO.class);
				for (CouponTargetDTO target : tmpTargetList) {
					CouponGetRuleEntity couponRule = new CouponGetRuleEntity();
			    	couponRule.setCouponId(couponId);
			    	String targetVal  = target.getTargetVal().replace(CouponConstants.USE_TARGET_PREFFIX.get(coupon.getGetTargetType()), "");
					couponRule.setTargetType(CouponConstants.COUPON_TARGET_TYPE.USE.getCode());
					couponRule.setTargetLimitType(coupon.getUseTargetType());
					couponRule.setTargetPro(target.getTargetPro());
					couponRule.setTargetVal(targetVal);
					couponRule.setCreater(coupon.getCreater());
					couponRule.setCreateTime(new Date());
					couponGetRuleDao.insert(couponRule);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BizException("保存优惠券失败" , e);
		}
    	return couponId;
    }

    /**
     * 分页查询优惠券信息
     * @param pageParam 分页参数
     * @param paramMap 查询参数
     * @return PageBean 分页参数和分页数据
     * @author xu_cc
     * @date 2017-11-16 11:11:20
     */
    @Override
    public PageBean listCouponPage(PageParam pageParam, Map<String, Object> paramMap) {
        return couponDao.listCouponPage(pageParam, paramMap);
    }

    /**
     * 根据ID查询用户信息
     * 
     * @param id
     *            用户id
     * @return couponEntity 用户对象
     * @author xu_cc
     * @date 2017-11-16 11:11:20
     */
    public CouponEntity getCouponById(Long id) {
        return couponDao.getById(id.longValue());
    }

    /**
     * 更新用户
     * 
     * @param couponEntity
     *            用户实体
     * @return Long 更新是否成功，>1代表更新成功
     * @author xu_cc
     * @date 2017-11-16 11:11:20
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateCoupon(CouponEntity coupon) {
        int result;
		try {
			result = couponDao.updateCoupon(coupon);
			long couponId = coupon.getId();
			// 删除优惠券已经使用的类
			couponGetRuleDao.deleteRuleByCoupon(couponId);
			
			// 保存领取、使用限制类型
			String getTargetList = coupon.getGetTargetList();
			if(StringUtil.isNotEmpty(getTargetList)){
				String[] tmpTargetArr  = getTargetList.split(",");
				for (String target : tmpTargetArr) {
					CouponGetRuleEntity couponRule = new CouponGetRuleEntity();
			    	couponRule.setCouponId(couponId);
					target = target.replace(CouponConstants.GET_TARGET_PREFFIX.get(coupon.getGetTargetType()), "");
					couponRule.setTargetType(CouponConstants.COUPON_TARGET_TYPE.GET.getCode());
					couponRule.setTargetPro(target);
					couponRule.setCreater(coupon.getCreater());
					couponRule.setCreateTime(new Date());
					couponGetRuleDao.insert(couponRule);
				}
			}
			
			// 保存领取、使用限制类型
			String useTargetList = coupon.getGetTargetList();
			if(StringUtil.isNotEmpty(useTargetList)){
				String[] tmpTargetArr  = useTargetList.split(",");
				for (String target : tmpTargetArr) {
					CouponGetRuleEntity couponRule = new CouponGetRuleEntity();
			    	couponRule.setCouponId(couponId);
					target = target.replace(CouponConstants.USE_TARGET_PREFFIX.get(coupon.getGetTargetType()), "");
					couponRule.setTargetType(CouponConstants.COUPON_TARGET_TYPE.USE.getCode());
					couponRule.setTargetPro(target);
					couponRule.setCreater(coupon.getCreater());
					couponRule.setCreateTime(new Date());
					couponGetRuleDao.insert(couponRule);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BizException("修复优惠券失败", e);
		}
    	return result;
    }

    /**
     * 根据条件查询优惠券信息
     * 
     * @param param
     * @return 数据列表
     * @author xu_cc
     * @date 2017-11-16 11:11:20
     */
    @Override
    public List<CouponEntity> listCoupon(Map<String, Object> param) {
        return couponDao.listCoupon(param);
    }

    /**
     * 删除优惠券信息
     * 
     * @param
     * @return int 返回删除记录条数
     * @author xu_cc
     * @date 2017-11-16 11:11:20
     */
    public int deleteCouponById(long id) {
        return couponDao.deleteById(id);
    }

    /**
     * 用于下拉列表（活动赠优惠券）
     * 
     * @param param
     * @return List<CouponEntity>
     * @author xu_cc
     * @throws Exception
     *             exception
     * @Date 创建时间：2017年11月21日 下午4:39:04
     */
    @Override
    public List<CouponEntity> listByPromotionCombo(Date beginTime, Date endTime) {
        if (null == beginTime || null == endTime) {
            return null;
        }
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("beginTime", beginTime);
        param.put("endTime", endTime);
        return couponDao.listByPromotionCombo(param);
    }
    
    /**
     * 查询客户的优惠券
     * @param param
     * @return
     */
	public List<CouponEntity> listUserCoupon(Map<String, Object> param){
		return couponDao.listUserCoupon(param);
	}

    /**
     * 查询可发放优惠券用户
     * @param pageParam
     * @param paramMap
     * @return
     * @author xkl
     * @date 2017年12月23日 下午2:04:59
     */
	@Override
	public PageBean listCouponCustomerPage(PageParam pageParam, Map<String, Object> paramMap) {
		return couponDao.listCouponCustomerPage(pageParam, paramMap);
	}

	/**
	 * 查询所有可发放优惠券用户
	 * @param paramMap
	 * @return
	 * @author xkl
	 * @date 2018年1月13日 上午10:47:35
	 */
	@Override
	public List<Map<String,Object>> listCouponCustomer(Map<String, Object> paramMap) {
		return couponDao.listCouponCustomer(paramMap);
	}

}
